package com.zzg.springboot.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.zzg.springboot.handler.MyAuthenticationFailureHandler;
import com.zzg.springboot.handler.MyAuthenticationSucessHandler;
import com.zzg.springboot.security.service.CustomUserDetailsService;
import com.zzg.springboot.validate.ValidateCodeFilter;

@Configuration // spring-security 配置文件类
@EnableWebSecurity // 启动spring-security 框架
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
	  	@Autowired
	    private MyAuthenticationSucessHandler authenticationSucessHandler;

	    @Autowired
	    private MyAuthenticationFailureHandler authenticationFailureHandler;

	    @Autowired
	    private ValidateCodeFilter validateCodeFilter;
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(validateCodeFilter,UsernamePasswordAuthenticationFilter.class).
		authorizeRequests().antMatchers("/", "/home","/code/image").permitAll().anyRequest().authenticated().and().formLogin()
				.loginPage("/login").successHandler(authenticationSucessHandler).failureHandler(authenticationFailureHandler).permitAll().and().logout().permitAll();
	}

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService());
    }
	
    /**
     * 自定义UserDetailsService，从数据库中读取用户信息
     * @return
     */
    @Bean
    public CustomUserDetailsService customUserDetailsService(){
        return new CustomUserDetailsService();
    }

}
